package com.maodou.android.ui.page.home

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import androidx.activity.ComponentActivity
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectHorizontalDragGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.hjq.permissions.permission.PermissionLists
import com.maodou.android.R
import com.maodou.android.automator.AppAccessibilityService
import com.maodou.android.automator.FloatingOverlayService
import com.maodou.android.ui.page.AccountDetailKey
import com.maodou.android.ui.page.EditAccountKey
import com.maodou.android.ui.page.Verify2faKey
import com.maodou.android.utils.PublicUtils.formatTimestampMs
import com.maodou.android.viewmodel.account.AccountViewModel
import com.maodou.android.viewmodel.main.MainViewModel
import com.maodou.core.datastore.db.table.AccountEntry
import com.maodou.core.navigation.GlobalUiBus
import com.maodou.core.navigation.Navigator3
import com.maodou.core.ui.components.AppAsyncImage
import com.maodou.core.ui.components.AppText
import com.maodou.core.ui.components.AvatarImage
import com.maodou.core.ui.components.EmptyCenterLayout
import com.maodou.core.ui.components.HSpacer
import com.maodou.core.ui.components.LoadMoreState
import com.maodou.core.ui.components.RefreshableLazyColumn
import com.maodou.core.ui.components.VSpacer
import com.maodou.core.ui.components.debouncedClickable
import com.maodou.core.utils.Logger
import com.maodou.core.utils.permission.PermissionUtils
import com.maodou.core.utils.toastOnUi
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt

/**
 * @Author Xing
 * @CreateTime 2025年09月17日
 * @Description 分类账号页面
 */
@Composable
fun TabPageUI(
    tabIndex: Int,
    listState: LazyListState? = null,
    type: String,
    isActive: Boolean = true,
    viewModel: AccountViewModel = hiltViewModel(),
) {
    val uiState by viewModel.uiState.collectAsStateWithLifecycle()
    var isLoading by remember(tabIndex, type) { mutableStateOf(false) }
    var loadingMore by remember(tabIndex, type) { mutableStateOf(false) }
    var selectedCount by remember(tabIndex) { mutableIntStateOf(0) }
    val lazyState = listState ?: rememberLazyListState()
    val scope = rememberCoroutineScope()
    // 多选状态
    var selectionMode by remember(tabIndex) { mutableStateOf(false) }
    val pageSize = 20
    LaunchedEffect(uiState.accountData) {
        selectedCount = uiState.accountData.filter { it.isSelect }.size
    }

    // 初始加载当前分类，仅在当前页激活时触发
    LaunchedEffect(type, isActive) {
        if (isActive) {
            viewModel.loadPageForType(type, page = 1, pageSize = pageSize, reset = true)
        }
    }

    // 监听筛选条件变化，当筛选条件改变时刷新列表
    LaunchedEffect(uiState.accountFilterParams, isActive) {
        if (isActive) {
            viewModel.loadPageForType(type, page = 1, pageSize = pageSize, reset = true)
        }
    }

    Column (Modifier.fillMaxSize()) {

        Box(
            modifier = Modifier.weight(1f)
        ){
            val loadMoreState = when {
                !isActive -> LoadMoreState.End
                loadingMore -> LoadMoreState.Loading
                uiState.isMore -> LoadMoreState.Idle
                else -> LoadMoreState.End
            }

            RefreshableLazyColumn(
                items = uiState.accountData,
                listState = lazyState,
                key = { item -> item.key },
                refreshing = isLoading,
                onRefresh = {
                    if (!isActive) return@RefreshableLazyColumn
                    isLoading = true
                    viewModel.loadPageForType(type, page = 1, pageSize = pageSize, reset = true){
                        scope.launch {
                            delay(1500)
                            isLoading = false
                        }
                    }
                    Logger.d("刷新数据: ${type}")
                },
                loadMoreState = loadMoreState,
                onLoadMore = {
                    if (!isActive || loadingMore) return@RefreshableLazyColumn
                    loadingMore = true
                    scope.launch {
                        viewModel.loadNextPageForType(type, pageSize = pageSize)
                        loadingMore = false
                    }
                    Logger.d("加载更多: ${type}")
                },
                contentPadding = PaddingValues(12.dp),
                emptyContent = { EmptyCenterLayout() }
            ) { item ->
                SwipeRevealContainer(
                    enableSwipe = !selectionMode,
                    onEdit = { Navigator3.navigate(EditAccountKey(item)) },
                    onDelete = { viewModel.onDeleteAccount(arrayListOf(item)) },
                    onItemLongPress = {
                        if (!selectionMode) {
                            selectionMode = true
                        }
                    },
                    onItemClick = {
                        Navigator3.navigate(AccountDetailKey(item))
                    }
                ) {
                    AccountCard(
                        item = item,
                        selectionMode = selectionMode,
                        onCheck = {
                            viewModel.onCheckAccount(arrayListOf(item))
                        },
                        onSelect = {
                            viewModel.onSelectAccount(item)
                        }
                    ) {
                        //todo 点击快速登录按钮
                        viewModel.downFile(item)
                    }
                }
            }
        }

        if (selectionMode && uiState.accountData.isNotEmpty()) {
            Column(modifier = Modifier.fillMaxWidth().padding(12.dp)) {
                if(selectedCount != 0) Box(
                    modifier = Modifier.background(color = Color(0xeeeeeeee), shape = RoundedCornerShape(topStart = 12.dp, topEnd = 12.dp)),
                    contentAlignment = Alignment.Center
                ) {
                    AppText(
                        text = "已选择${selectedCount}个账号",
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        style = TextStyle(
                            fontSize = 12.sp,
                            lineHeight = 14.sp
                        ),
                        modifier = Modifier.padding(horizontal = 20.dp, vertical = 6.dp)
                    )
                }

                Row(
                    modifier = Modifier
                        .shadow(2.dp, RoundedCornerShape(12.dp), clip = true)
                        .background(color = Color.White, RoundedCornerShape(12.dp))
                        .fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    ActionBottomItem(
                        if(uiState.isAllAccount) "取消" else "全选",
                        if(uiState.isAllAccount) R.mipmap.ic_home_bottom_select else R.mipmap.ic_home_bottom_unselect,
                        Modifier.weight(1f), true
                    ) {
                        viewModel.onSelectAccount()
                    }
                    ActionBottomItem("删除",R.mipmap.ic_home_bottom_delete, Modifier.weight(1f),uiState.accountData.any { it.isSelect }) {
                        viewModel.onDeleteAccount(uiState.accountData.filter { it.isSelect })
                    }
                    ActionBottomItem("导出",R.mipmap.ic_home_bottom_down, Modifier.weight(1f),uiState.accountData.any { it.isSelect }) {
                        viewModel.onExportAccount()
                    }
                    ActionBottomItem("检测",R.mipmap.ic_home_bottom_check, Modifier.weight(1f), uiState.accountData.any { it.isSelect }) {
                        val selected = uiState.accountData.filter { it.isSelect }
                        viewModel.startCheckSelectedAccounts(selected)
                    }
                    ActionBottomItem("关闭",R.mipmap.ic_home_bottom_close, Modifier.weight(1f),true) {
                        selectionMode = false
                    }
                }
            }
        }
    }
}

@Composable
fun AccountCard(item: AccountEntry,selectionMode:Boolean,onCheck:() -> Unit = {},onSelect:() -> Unit,onLogin:() -> Unit) {
    val context = LocalContext.current
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .shadow(elevation = 1.dp, shape = RoundedCornerShape(12.dp), clip = true)
            .background(Color(0xFFFFFFFF),RoundedCornerShape(12.dp))
    ) {
        Column(modifier = Modifier.padding(12.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
//                Image(
//                    painter = painterResource(R.mipmap.ic_facebook_logo),
//                    contentDescription = null,
//                    modifier = Modifier
//                        .size(46.dp)
//                        .clip(RoundedCornerShape(6.dp))
//                        .padding(2.dp),
//                )

                AppAsyncImage(
                    model = "http://graph.facebook.com/${item.accountID}/picture?type=square",
                    modifier = Modifier.size(46.dp)
                        .clip(RoundedCornerShape(12.dp)),
                    placeholderRes = if(item.platform == "Instagram") R.mipmap.ic_instagram_logo else R.mipmap.ic_facebook_logo,
                    errorRes = if(item.platform == "Instagram") R.mipmap.ic_instagram_logo else R.mipmap.ic_facebook_logo
                )

                HSpacer(8.dp)
                Column(modifier = Modifier.weight(1f).padding(end = 20.dp)) {
                    AppText(
                        text = item.nickname ?: item.type,
                        style = TextStyle(
                            fontSize = 14.sp,
                            fontWeight = FontWeight.SemiBold
                        ),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                    VSpacer(4.dp)
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.debouncedClickable {
                            val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                            val clip = ClipData.newPlainText("label", item.accountID)
                            clipboard.setPrimaryClip(clip)
                            context.toastOnUi("复制完成")
                        }
                    ) {
                        AppText(
                            text = item.accountID,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            style = TextStyle(
                                fontSize = 12.sp
                            )
                        )
                        HSpacer(3.dp)
                        Image(
                            painter = painterResource(R.mipmap.ic_copy_account),
                            contentDescription = null
                        )
                    }
                }
                // 在线状态
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(
                        modifier = Modifier
                            .size(10.dp)
                            .clip(RoundedCornerShape(50))
                            .padding(0.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        Surface(
                            color = if (item.online == 1) Color(0xFFF2994A) else if(item.online == 2)Color(0xFF27AE60) else Color(0xFFE74C3C),
                            shape = RoundedCornerShape(50)
                        ) { Spacer(Modifier.size(10.dp)) }
                    }
                    HSpacer(4.dp)
                    AppText(
                        text = if (item.online == 1) "待检测" else if(item.online == 2) "存活中" else "被封禁",
                        style = MaterialTheme.typography.bodySmall.copy(fontSize = 10.sp),
                        color = if (item.online == 1) Color(0xFFF2994A) else if(item.online == 2)Color(0xFF27AE60) else Color(0xFFE74C3C),
                        modifier = Modifier
                    )
                }
            }

            VSpacer(8.dp)
            FlowRow(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                item.tags?.split(",")?.forEach { TagChip(it) }
            }

            VSpacer(8.dp)
            if(item.lastCheck != null) Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                AppText(text = "上次检测", style = TextStyle(fontSize = 12.sp), color = MaterialTheme.colorScheme.onSurfaceVariant)
                AppText(text = "${formatTimestampMs(item.lastCheck ?: 0L,"MM-dd HH:mm")}", style = TextStyle(fontSize = 12.sp), color = MaterialTheme.colorScheme.onSurfaceVariant)
            }

            VSpacer(12.dp)
            Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) {
                ActionButtonSmall(text = "账号检测", color = Color(0xFFF2994A),true) {
                    onCheck()
                }
                HSpacer(8.dp)
                if(item.twoFa != null){
                    ActionButtonSmall(text = "2FA验证码", color = Color(0xFF2F80ED),true) {
                        Navigator3.navigate(Verify2faKey(item))
                    }
                    HSpacer(8.dp)
                }
                ActionButtonSmall(text = "快速登录", color = Color(0xFF27AE60),true) {
                    val permissions = arrayListOf(
                        PermissionLists.getBindAccessibilityServicePermission(
                            AppAccessibilityService::class.java),
                        PermissionLists.getBindVpnServicePermission(),
                        PermissionLists.getSystemAlertWindowPermission()
                    )
                    PermissionUtils.requestPermissions(permissions) {
                        Logger.d("获取完权限，开始自动登录")
                        FloatingOverlayService.start(context)
                        onLogin()
                    }
                }
            }
        }
        if(selectionMode) Box(
            modifier = Modifier.fillMaxSize().background(color = Color(0x11000000),RoundedCornerShape(12.dp)).matchParentSize()
                .debouncedClickable { onSelect() }
        ) {
            Image(
                painter = painterResource(if (item.isSelect) R.mipmap.ic_account_check else R.mipmap.ic_account_uncheck),
                null,
                modifier = Modifier.align(Alignment.TopEnd).clip(RoundedCornerShape(topEnd = 12.dp))
            )
        }
    }
}

@Composable
fun TagChip(text: String) {
    Box (
        modifier = Modifier.height(20.dp).background(Color(0xFFF2F2F2),RoundedCornerShape(4.dp)),
        contentAlignment = Alignment.Center
    ) { Text(text = text, modifier = Modifier.padding(horizontal = 8.dp), fontSize = 11.sp, lineHeight = 12.sp) }
}

@Composable
fun ActionButtonSmall(text: String, color: Color,enabled:Boolean, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        border = BorderStroke(1.dp,color),
        shape = RoundedCornerShape(6.dp),
        colors = ButtonColors(
            Color.Transparent,
            Color.Transparent,
            Color.Transparent,
            Color.Transparent,
        ),
        enabled = enabled,
        contentPadding = PaddingValues(vertical = 0.dp, horizontal = 12.dp),
        modifier = Modifier.height(32.dp),
    ) { Text(text = text, color = color, lineHeight = 14.sp, modifier = Modifier, fontSize = 12.sp) }
}

@Composable
fun ActionBottomItem(text: String,icon:Int,modifier: Modifier,isEnabled:Boolean,onClick: () -> Unit){
    val context = LocalContext.current
    Column(
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = modifier.padding(vertical = 16.dp)
            .debouncedClickable{
                if(!isEnabled) context.toastOnUi("请选择账号")
                else onClick()
            },
    ) {
        Image(
            painter = painterResource(icon),
            null,
            modifier = Modifier.size(32.dp)
        )
        VSpacer(4.dp)
        AppText(text = text, color = Color(0xff333333))
    }
}

@Composable
fun SwipeRevealContainer(
    actionsWidth: Int = 80,
    enableSwipe: Boolean = true,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
    onItemClick: (() -> Unit)? = null,
    onItemLongPress: (() -> Unit)? = null,
    content: @Composable () -> Unit
) {
    val density = LocalDensity.current
    val actionsWidthPx = with(density) { actionsWidth.dp.toPx() }

    var offsetX by remember { mutableFloatStateOf(0f) }
    var itemHeightPx by remember { mutableIntStateOf(0) }

    val swipeModifier = if (enableSwipe) {
        Modifier.pointerInput(Unit) {
            detectHorizontalDragGestures(
                onDragEnd = {
                    val threshold = actionsWidthPx / 2
                    offsetX = if (-offsetX > threshold) -actionsWidthPx else 0f
                },
                onHorizontalDrag = { _, dragAmountX ->
                    val newOffset = (offsetX + dragAmountX).coerceIn(-actionsWidthPx, 0f)
                    offsetX = newOffset
                }
            )
        }
    } else Modifier

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 12.dp)
            .then(swipeModifier)
    ) {
        Column (
            modifier = Modifier
                .align(Alignment.CenterEnd)
                .width(actionsWidth.dp)
                .height(with(density) { itemHeightPx.toDp() }),
        ) {
            // 编辑
            Surface(color = Color(0xFFBDBDBD),shape = RoundedCornerShape(topEnd = 12.dp), modifier = Modifier.fillMaxWidth().height(with(density) { (itemHeightPx / 2f).toDp() })) {
                Box(Modifier.fillMaxSize().clickable {
                    offsetX = 0f
                    onEdit()
                                                     }, contentAlignment = Alignment.Center) {
                    Text("编辑", color = Color.White, fontWeight = FontWeight.Normal)
                }
            }
            // 删除
            Surface(color = Color(0xFFE53935),shape = RoundedCornerShape(bottomEnd = 12.dp), modifier = Modifier.fillMaxWidth().height(with(density) { (itemHeightPx / 2f).toDp() })) {
                Box(Modifier.fillMaxSize().clickable {
                    offsetX = 0f
                    onDelete()
                                                     }, contentAlignment = Alignment.Center) {
                    Text("删除", color = Color.White, fontWeight = FontWeight.Normal)
                }
            }
        }

        // 前景内容
        Box(
            modifier = Modifier
                .offset { IntOffset(offsetX.roundToInt(), 0) }
                .fillMaxWidth()
                .onSizeChanged { itemHeightPx = it.height }
                .combinedClickable(
                    onClick = { onItemClick?.invoke()},
                    onLongClick = { onItemLongPress?.invoke() },
                    interactionSource = remember { MutableInteractionSource() },
                    indication = null
                )
        ) {
            content()
        }
    }
}

@Preview
@Composable
fun AccountCardPreview(){
    AccountCard(
        AccountEntry(
        key = "-2",
        userId = "9999",
        nickname = "账号名 / 备注",
            accountID = "641561651683",
        tags = listOf("手机号", "密码", "邮箱", "Cookie", "IP").joinToString(","),
        type = "个人号",
        online = 1,
        lastCheck = System.currentTimeMillis()
    ),false, onSelect = {}){}
}